# coding=utf8
import json

import falcon

from logging import getLogger

from libs.help import stream_to_params
from models.user.info import model_user_info
from Crypto.Hash import SHA512

logger = getLogger('base')


class StatusResource:
    def on_options(self, req, resp):
        resp.status = falcon.HTTP_200  # This is the default status
        resp.set_header('Access-Control-Allow-Origin', '*')
        resp.set_header('Access-Control-Allow-Headers', 'uid')
        resp.set_header('Access-Control-Allow-Methods', 'POST,GET')

    def on_post(self, req, resp):
        data = req.stream.read().decode()
        data = stream_to_params(data)

        user_info = model_user_info.coll.find_one({
            'Login': data['login']
        })
        resp.status = falcon.HTTP_200  # This is the default status
        resp.set_header('Access-Control-Allow-Origin', '*')
        resp.set_header('Access-Control-Allow-Methods', 'POST')
        resp.set_header('Access-Control-Allow-Headers', 'uid')
        if user_info is None or user_info['PassWd'] != SHA512.new(data['passwd'].encode()).hexdigest():
            resp.body = json.dumps({
                'info': {
                    'code': 501,
                    'codeMessage': '用户名密码错误'
                }
            })
        else:
            uid = str(user_info['_id'])
            resp.body = json.dumps({
                'info': {
                    'code': 200
                },
                'item': {
                    'username': user_info['UserName'],
                    'uid': uid,
                    'role': user_info['Role'] if 'Role' in user_info else 1
                }
            })
